package com.jcark.utilscode

import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.ItemDecoration
import androidx.recyclerview.widget.StaggeredGridLayoutManager

class StaggerItemDecoration(space: Int) : ItemDecoration() {
    private var space = 0
    private var isTopSpace = true

    init {
        this.space = space
        this.isTopSpace = isTopSpace
    }

    override fun getItemOffsets(
        outRect: Rect,
        view: View,
        parent: RecyclerView,
        state: RecyclerView.State
    ) {
        val lp = view.layoutParams
        val mg = parent.layoutManager
        var spanCount = 0
        if (mg is StaggeredGridLayoutManager) {
            spanCount = mg.spanCount
        }
        if (lp is StaggeredGridLayoutManager.LayoutParams) {
            if (isTopSpace && spanCount >= 0) {
                outRect.top = space
            }
            if (lp.spanIndex % 2 == 0) {
                outRect.left = space
                outRect.right = space / 2
            } else {
                outRect.left = space / 2
                outRect.right = space
            }
        }
    }
}